/*
 * @Author: your name
 * @Date: 2024-11-11 08:00:46
 * @LastEditTime: 2024-11-13 22:05:42
 * @LastEditors: YN
 * @Description: In User Settings Edit
 * @FilePath: \index\src\main\java\com\yuni\index\Service\Impl\EmailServiceImpl.java
 */
package com.yuni.index.Service.Impl;

import com.yuni.index.Service.EmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Properties;
import java.util.Random;

import jakarta.annotation.PostConstruct;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String senderEmail;

    @Value("${spring.mail.password}")
    private String authCode;

    @PostConstruct
    public void init() {
        if (senderEmail == null || senderEmail.isEmpty() || authCode == null || authCode.isEmpty()) {
            throw new IllegalStateException("Email credentials are not set properly in configuration.");
        }
        System.out.println("Sender Email: " + senderEmail);
        System.out.println("Auth Code: " + authCode);
    }




    // 生成验证码
    @Override
    public String generateCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000));
    }

    // 发送验证码邮件
    @Override
    public void sendEmail(String recipientEmail, String code) throws MessagingException {
        if (senderEmail == null || authCode == null) {
            throw new IllegalArgumentException("Email credentials are not set properly.");
        }

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true"); // 启用 SSL
        props.put("mail.smtp.ssl.protocols", "TLSv1.2"); // 显式指定使用TLSv1.2协议

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(senderEmail, authCode);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
            message.setSubject("您的验证码");
            message.setText("您的验证码是：" + code + "，五分钟内有效，请谨慎使用，如果这封邮件不是您本人操作，请忽略");
            Transport.send(message);
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new MessagingException("发送失败: " + e.getMessage());
        }
    }
}